package com.zwz.crawler.tendering;

import com.zwz.constant.Constant;
import com.zwz.parse.JsonParserUtil;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@Slf4j
public class TungeeWinningStats {
    public static void startTungeeWinningStats( ) throws UnsupportedEncodingException {
        // 构建请求参数
        String nameId = "577de19eadf21dc4";
        String encodedNameId = URLEncoder.encode(nameId, "utf-8");
        String url = "https://sales.tungee.com/api/winning/statistics?nameId=" + encodedNameId;

        try {
            Connection.Response response = Jsoup.connect(url)
                    .method(Connection.Method.GET)
                    // 设置完整请求头
                    .header("authority", "sales.tungee.com")
                    .header("accept", "*/*")
                    .header("accept-encoding", "gzip, deflate, br, zstd")
                    .header("accept-language", "zh-CN,zh;q=0.9")
                    .header("cache-control", "no-cache")
                    .header("pragma", "no-cache")
                    .header("priority", "u=1, i")
                    .header("referer", "https://sales.tungee.com/enterprise-details/577de19eadf21dc4/enterprise-information/bidding")
                    .header("sec-ch-ua", "\"Not;A=Brand\";v=\"24\", \"Chromium\";v=\"128\"")
                    .header("sec-ch-ua-mobile", "?0")
                    .header("sec-ch-ua-platform", "\"Windows\"")
                    .header("sec-fetch-dest", "empty")
                    .header("sec-fetch-mode", "cors")
                    .header("sec-fetch-site", "same-origin")
                    .header("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36")
                    .header("x-tonxis-pid", "67864ea75f69e05d3b544ca7")
                    // 设置完整Cookie（需替换为浏览器最新值）
//                    .header("cookie", "_tx_pid=67864ea75f69e05d3b544ca7; __wpkreporterwid_=cc4a07fc-7bb9-40a4-96bc-2cbac34b658f; __last_enter_version=sales; _co_i=6805a5576eceb9637696f09d; _tx_uid=680701dddca941522b77e864; _tx_cid=6805a5576eceb9637696f09d; DISTINCT_ID=b84fe276-099f-4932-92b3-d54b92ae384b; _tx_sid=MTc0NTMwMTE0MzYyMjo4MmQ2OTQ5MTY0NjU2ODNmYjQ5MjlmMjc3NDg5ZDFlZg==; Hm_lvt_f2ee75449fc055cc4dbceb4fe403bea3=1745301094,1745302709; HMACCOUNT=B4E402DF057C895E; SecurityCenterDuId=ImFBSG15RzdPdVdPdCtsWnNGMFVuSXhVPSI.GujnjA.YBo4Zvc8vs4jgEmtioacknOQ9pE; tg_referrer_source=https%3A%2F%2Fuser.tungee.com%2F; Hm_lpvt_f2ee75449fc055cc4dbceb4fe403bea3=1745311256; acw_tc=1a0c399c17453774119646163e0075ab798fc34903e67c7d6c26b928bcee49; accountCenterSessionId=.eJwljrFOxDAQRP_F9RW73o3tuw7IiYZLmkNIaaK1vVaIoiAlOUAg_p0IyhnNe5pv079mczIkFEpAjKCUHeWCJThUzBo1Fo9eSUKyMQMLK3NKyXshAAuS4AgAvgTKIbAII_lIUqRKnm2qgCRmriBjdMABrGPMrBZsUdrN2ZOag-nLoutgTtty04OZVXO_yrv221ufozkVmda9v626_F92AXzlIDlNGo-OojKitXZXpUHmWad99KFxz-sf0NbD0Hwl7Ornra27oXsAaK_N-PRy_mweL1sz3lWXazc19Zm68X4wP78weVR_.Gunrwg.58TJ6T_AwcFfNSp69QPgHJlRnvA; doncusSessionId=eyJfZnJlc2giOmZhbHNlLCJ1c2VyX2lkIjoiNjgwNzAxZGRkY2E5NDE1MjJiNzdlODY0In0.GunryA.wSaW981AWiwP3DVNXUDiaUgnsF8")
                    .header("cookie", Constant.cookies)
                    .ignoreContentType(true)
                    .ignoreHttpErrors(true)
                    .maxBodySize(0)
                    .timeout(30000)
                    .execute();

           log.info("HTTP状态码: " + response.statusCode());
           //log.info("响应内容:\n" + response.body());
            handleErrorCases(response);

            //解析
            JsonParserUtil.ParseTending(response.body());

        } catch (IOException e) {
            System.err.println("请求异常: " + e.getMessage());
            e.printStackTrace();
        }
    }

    private static void handleErrorCases(Connection.Response response) {
        switch (response.statusCode()) {
            case 401:
                System.err.println("[认证失效] 解决方案：");
                System.err.println("1. 通过浏览器登录更新Cookie（重点关注 accountCenterSessionId）");
                System.err.println("2. 检查是否需要动态签名（对比浏览器请求头中的 x-tonxis-signature）");
                break;
            case 403:
                System.err.println("[权限不足] 请确认：");
                System.err.println("1. nameId 是否属于当前账户");
                System.err.println("2. 当前套餐是否包含招投标数据权限");
                break;
            case 404:
                System.err.println("[接口路径错误] 请检查：");
                System.err.println("当前路径: " + response.url());
                break;
            case 429:
                System.err.println("[请求频繁] 建议：");
                System.err.println("1. 添加3-5秒随机延时");
                System.err.println("2. 使用代理IP池轮换");
                break;
            default:
                if (response.statusCode() != 200) {
                    System.err.println("未知错误码: " + response.statusCode());
                }
        }
    }
}
